package v1

import (
	"RoccBlog/global"
	"RoccBlog/initalize"
	"RoccBlog/model"
	v1 "RoccBlog/repository/v1"
	"RoccBlog/service"
	"RoccBlog/util/constant"
	"context"
	"github.com/gin-gonic/gin"
)

type CacheService struct {
	service.BaseService
	service.BaseOperationService
	Repository v1.CacheRepository
}

func init() {
	global.RegisterService(&CacheService{
		Repository: v1.CacheRepository{},
	})
}

func (s *CacheService) Add(ctx *gin.Context, data model.Cache) error {
	err := s.Repository.Create(data)
	if err != nil {
		return err
	}
	return nil
}

func (s *CacheService) Remove(ctx *gin.Context, id int) error {
	err := s.Repository.Delete(id)
	if err != nil {
		return err
	}
	refreshGlobalCache()
	return nil
}

func (s *CacheService) Modify(ctx *gin.Context, data model.Cache) error {
	err := s.Repository.Update(data)
	if err != nil {
		return err
	}
	refreshGlobalCache()
	return nil
}

func (s *CacheService) FindById(ctx *gin.Context, id int) (model.Cache, error) {
	return s.Repository.SelectById(id)
}

func (s *CacheService) Find(ctx *gin.Context) (any, error) {
	size, num := s.GetPage(ctx)
	list, err := s.Repository.Select(num, size)
	if err != nil {
		return nil, err
	}

	return list, err
}

func (s *CacheService) RemoveCacheValue(id int) error {
	return s.Repository.DeleteCacheValue(id)
}

func (s *CacheService) AddCacheValue(value model.CacheValue) error {
	err := s.Repository.CreateCacheValue(value)
	if err != nil {
		return err
	}
	refreshGlobalCache()
	return nil
}

// GetGlobalCacheValue 获取全局缓存值
func (s *CacheService) GetGlobalCacheValue(ctx context.Context) (any, error) {
	//获取公共缓存值
	commons, err := global.RedisClient.HGet(ctx, constant.GlobalCacheKey, constant.GlobalCommonsCacheKey).Result()
	database, err := global.RedisClient.HGet(ctx, constant.GlobalCacheKey, constant.GlobalDatabaseCacheKey).Result()
	if err != nil {
		return nil, err
	}
	globalCache := gin.H{
		"commons":  commons,
		"database": database,
	}
	return globalCache, err
}

// refreshGlobalCache 刷新全局缓存
func refreshGlobalCache() {
	initalize.RefreshCacheValue()
}
